"""日志模块"""

import os
import logging
import logging.handlers
from datetime import datetime
from pathlib import Path
from typing import Optional

class CommandLogger:
    """命令日志记录器"""

    def __init__(self):
        self._logger = logging.getLogger('bera')
        self._current_command: Optional[str] = None
        self._current_table: Optional[str] = None

        # 确保日志目录存在
        self._log_dir = Path('artifacts/logs')
        self._log_dir.mkdir(parents=True, exist_ok=True)

        # 防止日志重复
        if not self._logger.handlers:
            self._logger.setLevel(logging.INFO)
            # 设置日志器不传播到父级
            self._logger.propagate = False

            # 设置控制台处理器
            console_handler = logging.StreamHandler()
            console_handler.setLevel(logging.INFO)
            console_formatter = logging.Formatter(
                '%(asctime)s [%(levelname)s]: %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S'
            )
            console_handler.setFormatter(console_formatter)
            self._logger.addHandler(console_handler)

    def set_command(self, command_name: str, table_name: Optional[str] = None):
        """设置当前命令名称和表名"""
        self._current_command = command_name
        self._current_table = table_name

        # 移除旧的文件处理器
        for handler in self._logger.handlers[:]:
            if isinstance(handler, logging.FileHandler):
                self._logger.removeHandler(handler)

        # 创建新的文件处理器
        if command_name:
            date_str = datetime.now().strftime('%Y%m%d%H%M%S')
            if table_name:
                log_file = self._log_dir / f"{command_name}-{table_name}.{date_str}.txt"
            else:
                log_file = self._log_dir / f"{command_name}.{date_str}.txt"

            file_handler = logging.FileHandler(log_file, encoding='utf-8')
            file_handler.setLevel(logging.INFO)
            file_formatter = logging.Formatter(
                '%(asctime)s [%(levelname)s] %(name)s: %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S'
            )
            file_handler.setFormatter(file_formatter)
            self._logger.addHandler(file_handler)

    def debug(self, msg: str, *args, **kwargs):
        """记录调试级别日志"""
        self._logger.debug(msg, *args, **kwargs)

    def info(self, msg: str, *args, **kwargs):
        """记录信息级别日志"""
        self._logger.info(msg, *args, **kwargs)

    def warning(self, msg: str, *args, **kwargs):
        """记录警告级别日志"""
        self._logger.warning(msg, *args, **kwargs)

    def error(self, msg: str, *args, **kwargs):
        """记录错误级别日志"""
        self._logger.error(msg, *args, **kwargs)

    def critical(self, msg: str, *args, **kwargs):
        """记录严重错误级别日志"""
        self._logger.critical(msg, *args, **kwargs)

# 创建全局日志记录器实例
logger = CommandLogger()
